const { verifyParams } = require('../utils/utils')
const logger = require('../utils/log4js')
const UserModel = require('../model/user.model')
const { generateToken } = require('../utils/jwt')

module.exports = async (req, res) => {
    let verify = verifyParams(req.body, [
        {
            key: 'email',
            rule: [
                { required: true, error: '请输入邮箱!' },
                { type: 'string', error: '邮箱格式错误!'  },
                { pattern: /^([A-Za-z0-9_\-\.])+\@([A-Za-z0-9_\-\.])+\.([A-Za-z]{2,4})$/, error: '邮箱格式错误!' }
            ]
        },
        {
            key: 'pwd',
            rule: [
                { required: true, error: '请输入密码!' },
                { type: 'string', error: '密码格式错误!' },
                { pattern: /^(?=.*\d)(?=.*[A-z])[\da-zA-Z]{4,16}$/, error: '密码应为4-16位的字母、数字组成!' },
            ]
        }
    ])
    if (verify) return res.json({ code: 0, msg: verify })

    let { email, pwd } = req.body
    try {
        const user = await UserModel.findOne({
            email,
            pwd
        }, '-pwd').lean()
        if (user) {
            let token = generateToken(user)
            res.json({ code: 1, msg: '登录成功!', data: { userInfo: user, token } })
        } else {
            res.json({ code: 0, msg: '用户名或密码错误!' })
        }
    } catch (e) {
        res.json({ code: 0, msg: e })
    }
}